package tcm.com.gistone.controller;

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import tcm.com.gistone.database.config.GetBySqlMapper;
import tcm.com.gistone.database.entity.Theme;
import tcm.com.gistone.database.entity.Word;
import tcm.com.gistone.database.mapper.*;
import tcm.com.gistone.util.ClientUtil;
import tcm.com.gistone.util.EdatResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:renqiang
 * @Param:
 * @Description:
 * @Date:15:08 2017/7/14
 */
@RestController
@RequestMapping("topo")
@Transactional
public class TopoController {
    @Autowired
    private GetBySqlMapper gm;
    @Autowired
    private WordMapper wm;
    @Autowired
    WordRelationMapper wrm;
    @Autowired
    ThemeMapper tm;
    @Autowired
    SectionMapper sm;
    @Autowired
    SpecialBookMapper sbm;
    @Autowired
    WsRelationMapper wsm;

    /*根据关键词查询一本书中的主题关系*/
    @RequestMapping(value = "getRelationWithBookId", method = RequestMethod.POST)
    public EdatResult getRelationWithBookId(HttpServletRequest request,
                                            HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request
                    .getParameter("data"));
            String keyWord = data.getString("keyWord");
            long wordType = data.getLong("type");
            long specialId = 0;
            if (!data.getString("specialId").equals("")) {
                specialId = data.getLong("specialId");
            }
            long bookId = data.getLong("bookId");
            Word word = wm.selectByWord(specialId, keyWord, wordType);
            if (null == word) {
                return EdatResult.build(1, "没有找到该主题词");
            }
            //String wordType = word.getThemeType();
            int type = (int) wordType;
            long wordId = word.getWordId();
            List<Map> result = new ArrayList<>();
            for (int i = 1; i < 10; i++) {
                if (type < i) {
                    Map map = new HashMap();
                    List<Map> list = wrm.selectByWordWithBook(type, i, wordId, bookId);
                    int num = list.size();
                    if (num > 0) {
                        for (Map map1 : list) {
                            Word word1 = wm.selectByPrimaryKey((Long) map1.get("wordId"));
                            map1.put("word", word1.getWord());
                        }
                        Theme theme = tm.selectByPrimaryKey((long) i);
                        map.put("name", theme.getThemeName());
                        map.put("wordNum", num);
                        map.put("words", list);
                        result.add(map);
                    }
                } else if (type > i) {
                    Map map = new HashMap();
                    List<Map> list = wrm.selectByAnoWordWithBook(i, type, wordId, bookId);
                    int num = list.size();
                    if (num > 0) {
                        for (Map map1 : list) {
                            Word word1 = wm.selectByPrimaryKey((Long) map1.get("wordId"));
                            map1.put("word", word1.getWord());
                        }
                        Theme theme = tm.selectByPrimaryKey((long) i);
                        map.put("name", theme.getThemeName());
                        map.put("wordNum", num);
                        map.put("words", list);
                        result.add(map);
                    }
                }
            }
            return EdatResult.build(0, "success", result);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }

    /*根据关键词查询一本书中与某主题的关联主题词*/
    @RequestMapping(value = "getRelatedWordsWithBookId", method = RequestMethod.POST)
    public EdatResult getRelatedWordsWithBookId(HttpServletRequest request,
                                                HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request
                    .getParameter("data"));
            Map map = new HashMap();
            long tid2 = data.getLong("targetType");// 匹配类
            String keyWord = data.getString("keyWord");// 搜索词
            long tid1 = data.getLong("type");
            long specialId = data.getLong("specialId");
            Word word = wm.selectByWord(specialId, keyWord, tid1);
            long wordId = word.getWordId();// 搜索词id
            long wordType = word.getThemeType();// 搜索词类
            long bookId = data.getLong("bookId");
            map.put("type", tid2);
            String sql = "SELECT DISTINCT tb_ws_relation.word_id as id , tb_ws_relation.word_type as type "
                    + "FROM tb_ws_relation join (SELECT section_id  FROM tb_ws_relation "
                    + " WHERE tb_ws_relation.word_id ="
                    + wordId
                    + ") b on tb_ws_relation.section_id=b.section_id where tb_ws_relation.book_id="
                    + bookId
                    + " and tb_ws_relation.word_type='"
                    + tid2
                    + "';";
            List<Map> result = new ArrayList<>();
            result = gm.findRecords(sql);// 搜索类匹配结果
            if (result.size() < 1) {
                return EdatResult.build(0, "没查到");
            }
            List<Map> list = new ArrayList<>();
            for (Map tem : result) {
                Map<String, Object> map1 = new HashMap();
                Word w = wm.selectByPrimaryKey((Long) tem.get("id"));
                int num = getNum(bookId, wordId, w.getWordId());
                map1.put("word", w.getWord());
                map1.put("id", (Long) tem.get("id"));
                map1.put("num", num);
                list.add(map1);
            }
            map.put("datas", list);
            return EdatResult.build(0, "success", map);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }

    /*根据关键词查询所有与所有主题的关系*/
    @RequestMapping(value = "getRelation", method = RequestMethod.POST)
    public EdatResult getRelation(HttpServletRequest request,
                                  HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request
                    .getParameter("data"));
            String keyWord = data.getString("keyWord");
            long specialId = data.getLong("specialId");
            long type = data.getLong("type");
            Word word = wm.selectByWord(specialId, keyWord, type);
            if (null == word) {
                return EdatResult.build(1, "没有找到该主题词");
            }
            List<Long> ids = sbm.selectBySpecial(specialId);
            long wordId = word.getWordId();
            List<Map> result = new ArrayList<>();
            for (int i = 1; i < 10; i++) {
                if (type < i) {
                    Map map = new HashMap();
                    List<Map> list = wrm.selectByWordWithSpecial(type, i, wordId, specialId);
                    int num = list.size();
                    if (num > 0) {
                        Theme theme = tm.selectByPrimaryKey((long) i);
                        map.put("name", theme.getThemeName());
                        map.put("wordNum", num);
                        map.put("words", list);
                        result.add(map);
                    }
                } else if (type > i) {
                    Map map = new HashMap();
                    List<Map> list = wrm.selectByAnoWordWithSpecial(i, type, wordId, specialId);
                    int num = list.size();
                    if (num > 0) {
                        Theme theme = tm.selectByPrimaryKey((long) i);
                        map.put("name", theme.getThemeName());
                        map.put("wordNum", num);
                        map.put("words", list);
                        result.add(map);
                    }
                }
            }
            return EdatResult.build(0, "success", result);
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }

    }

    /*获取两个主题词关联度*/
    public int getNum(long bookId, long word1, long word2) {
        String sql = "select a.numa,b.numb from (select section_id,word_num as numa from tb_ws_relation where book_id="
                + bookId
                + " and word_id ="
                + word1
                + " )a"
                + " join (select section_id,word_num as numb from tb_ws_relation where book_id ="
                + bookId
                + " and word_id = "
                + word2
                + ")b on a.section_id =b.section_id ";
        List<Map> result = new ArrayList<>();
        result = gm.findRecords(sql);// 搜索类匹配结果
        int num = 0;
        for (Map map : result) {
            int numa = Integer.parseInt(map.get("numa").toString());
            int numb = Integer.parseInt(map.get("numb").toString());
            if (numa < numb) {
                num += numa;
            } else {
                num += numb;
            }
        }
        return num;
    }

    /*获取关键词相关段落*/
    @RequestMapping(value = "getRelatedSection", method = RequestMethod.POST)
    public EdatResult getRelatedSection(HttpServletRequest request,
                                        HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request
                    .getParameter("data"));
            String keyWord = data.getString("keyWord");
            long wordType = data.getLong("type");
            long specialId = data.getLong("specialId");
            Word word = wm.selectByWord(specialId, keyWord, wordType);
            List<Map> result = new ArrayList<>();
            String sql = "SELECT  count(a.word_num)as total ,a.section_id  as sectionId ,a.book_id FROM tb_ws_relation a join (select book_id from tb_special_book where special_id = " + specialId +
                    " ) b on a.book_id = b.book_id where word_id = " + word.getWordId() + " group by section_id order by total desc limit 5;";
            result = gm.findRecords(sql);
            List<Map> res = new ArrayList<>();
            for (int i = 0; i < result.size(); i++) {
                Map map = new HashMap();
                long secId = (long) result.get(i).get("sectionId");
                map.put("num", result.get(i).get("total"));
                map.put("sectionId", secId);
                String content = sm.selectByPrimaryKey(secId).getSectionContent();
                map.put("content", content);
                res.add(map);
            }
            return EdatResult.ok(res);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }

    /*获取两个主题词的相关段落*/
    @RequestMapping(value = "getSectionWithTwoWords", method = RequestMethod.POST)
    public EdatResult getSectionWithTwoWords(HttpServletRequest request,
                                             HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            JSONObject data = JSONObject.fromObject(request
                    .getParameter("data"));
            long specialId = data.getLong("specialId");
            String word1 = data.getString("word1");
            String word2 = data.getString("word2");
            long type1 = data.getLong("type1");
            long type2 = data.getLong("type2");
            long wordId1 = wm.selectByWord(specialId, word1, type1).getWordId();//传  忽思慧
            long wordId2 = wm.selectByWord(specialId, word2, type2).getWordId();
            List<Map> result = new ArrayList<>();
            String sql = "select m.section_id as sectionId ,m.word_num as num1,n.word_num as num2 from (SELECT a.* FROM tb_ws_relation a join (select book_id from tb_special_book " +
                    "where special_id = " + specialId + ") b on a.book_id = b.book_id  where word_id= " + wordId1 + ")m join (SELECT c.* FROM tb_ws_relation c join (select book_id from " +
                    " tb_special_book where special_id = " + specialId + ") d on c.book_id = d.book_id where word_id= " + wordId2 + " )n on m.section_id = n.section_id limit 5 ;";
            result = gm.findRecords(sql);
            List<Map> res = new ArrayList<>();
            for (int i = 0; i < result.size(); i++) {
                Map map = new HashMap();
                long secId = (long) result.get(i).get("sectionId");
                map.put("num1", result.get(i).get("num1"));
                map.put("num2", result.get(i).get("num2"));
                map.put("sectionId", secId);
                String content = sm.selectByPrimaryKey(secId).getSectionContent();
                map.put("content", content);
                res.add(map);
            }
            return EdatResult.ok(res);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return EdatResult.build(1, "fail");
        }
    }
}
